package com.mzba.place.fragment;

import java.util.HashMap;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.text.style.RelativeSizeSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockFragment;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.map.Geometry;
import com.baidu.mapapi.map.Graphic;
import com.baidu.mapapi.map.GraphicsOverlay;
import com.baidu.mapapi.map.ItemizedOverlay;
import com.baidu.mapapi.map.MapController;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.OverlayItem;
import com.baidu.mapapi.map.Symbol;
import com.baidu.mapapi.search.MKAddrInfo;
import com.baidu.mapapi.search.MKBusLineResult;
import com.baidu.mapapi.search.MKDrivingRouteResult;
import com.baidu.mapapi.search.MKPoiResult;
import com.baidu.mapapi.search.MKSearch;
import com.baidu.mapapi.search.MKSearchListener;
import com.baidu.mapapi.search.MKSuggestionResult;
import com.baidu.mapapi.search.MKTransitRouteResult;
import com.baidu.mapapi.search.MKWalkingRouteResult;
import com.baidu.platform.comapi.basestruct.GeoPoint;
import com.mzba.place.PlaceApplication;
import com.mzba.place.R;
import com.mzba.place.adapter.MyArrayAdapter;
import com.mzba.place.ui.CautionsActivity;
import com.mzba.place.ui.MainActivity;
import com.mzba.place.utils.AppContext;
import com.mzba.place.utils.BasicUIEvent;
import com.mzba.place.utils.HttpUtils;
import com.mzba.place.utils.UICore;
import com.mzba.place.utils.UrlConfig;

/**
 * 
 * @author 06peng
 * 
 */
public class SettingFragment extends SherlockFragment implements Callback,BasicUIEvent{
	View view;
	private MapView mMapView;
	private PlaceApplication app;

	private MainActivity mainActivity;
	private LocationClient mLocClient;

	private Drawable myLocation;
	private MapController mMapController = null;
	private boolean isMoved;
	private int mLastMotionX, mLastMotionY;
	private int zoomLevel = 14;
	private int latitude;
	private int longitude;
	// 移动的阈值
	private static final int TOUCH_SLOP = 20;
	private Handler handler;
	public MKSearch mSearch = null;

	GraphicsOverlay graphicsOverlay = null;

	private TextView tv_location;
	private TextView tv_reporttype;
	private SpannableString ss;
    /**
     * 地图范围
     */
	private Spinner rangeSpinner;
	private ArrayAdapter<CharSequence> rangeAdapter;
	private EditText ed_address;
	private ImageView iv_address;
	/**
	 * 类型
	 */
	private Spinner reportTypeSpinner;
	private MyArrayAdapter reportTypeAdapter;

	/**
	 * 选中的半径 默认是15
	 */
	private double raidus;
	/**
	 * 
	 */
	private String raidusString[];
	private GeoPoint currentPoint;
	
	private Button btnMytips;
	
	private final int menu_confirm = 5;
	private String place;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mainActivity = (MainActivity) getSherlockActivity();
		app = (PlaceApplication) mainActivity.getApplication();
		if (app.mBMapManager == null) {
			app.mBMapManager = new BMapManager(mainActivity);
			app.mBMapManager.init(PlaceApplication.strKey,
					new PlaceApplication.MyGeneralListener());
		}
		handler = new Handler(this);
		raidusString = mainActivity.getResources().getStringArray(R.array.Range);
		mLocClient = app.mLocationClient;
		app.getMyListener().setHander(handler);

		myLocation = mainActivity.getResources().getDrawable(
				R.drawable.ic_map_current_position);
	}

	private void setLocationOption() {
		LocationClientOption option = new LocationClientOption();
		option.setOpenGps(true);
		option.setCoorType("bd09ll");	
		option.setAddrType("all");
		option.setScanSpan(0);
		option.setPriority(LocationClientOption.GpsFirst);
		option.setPoiNumber(10);
		option.disableCache(true);
		mLocClient.setLocOption(option);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		view = inflater.inflate(R.layout.framgnent_setting_map, null);
		initView();
		new Thread() {
			public void run() {
				setLocationOption();
				if (mLocClient != null && mLocClient.isStarted()) {
					mLocClient.requestLocation();
				} else {
					mLocClient.start();
					mLocClient.requestLocation();
				}
			};
		}.start();
		return view;
	}

	private void initView() {
		btnMytips = (Button) view.findViewById(R.id.button_mytips);
		btnMytips.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(mainActivity, CautionsActivity.class);
				mainActivity.startActivity(intent);
			}
		});
		mMapView = (MapView) view.findViewById(R.id.bmapView);
		tv_location = (TextView) view.findViewById(R.id.tv_location_point);
		tv_reporttype = (TextView) view.findViewById(R.id.tv_report_type_point);
		rangeSpinner = (Spinner) view.findViewById(R.id.sn_address);
		ed_address = (EditText) view.findViewById(R.id.et_address);
		iv_address = (ImageView) view.findViewById(R.id.iv_address);
		String text = this.getString(R.string.location_point);

		ss = new SpannableString(text);
		ss.setSpan(new RelativeSizeSpan(1.2f), 0, 8,
				Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
		ss.setSpan(new ForegroundColorSpan(mainActivity.getResources()
				.getColor(R.color.setting_green)), 8, 23,
				Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
		tv_location.setText(ss);

		text = this.getString(R.string.reporttype_point);
		ss = new SpannableString(text);
		ss.setSpan(new RelativeSizeSpan(1.2f), 0, 7,
				Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
		ss.setSpan(new ForegroundColorSpan(mainActivity.getResources()
				.getColor(R.color.setting_green)), 7, 20,
				Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
		tv_reporttype.setText(ss);

		rangeAdapter = ArrayAdapter.createFromResource(mainActivity,R.array.distanceRange, R.layout.spinner_item);
		rangeAdapter.setDropDownViewResource(R.layout.sherlock_spinner_dropdown_item);
		rangeSpinner.setAdapter(rangeAdapter);
		rangeSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {

				TextView tv = (TextView) arg1;
				if (tv != null) {
					tv.setTextColor(Color.BLACK);
				}
				// TODO 还无保存
				raidus = Double.parseDouble(raidusString[arg2]) * 1000;
				testCircleClick(currentPoint, raidus);
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {

			}
		});
		int spinnerPosition = rangeAdapter.getPosition(rangeAdapter.getItem(1));
		rangeSpinner.setSelection(spinnerPosition);

		reportTypeSpinner = (Spinner) view.findViewById(R.id.report_type_spinner);

		// reportTypeAdapter = ArrayAdapter.createFromResource(mainActivity,
		// R.array.reportType, R.layout.spinner_item);
		reportTypeAdapter = new MyArrayAdapter(mainActivity,
				R.layout.spinner_item);
		reportTypeAdapter.addAll(getResources().getStringArray(
				R.array.reportType));
		reportTypeAdapter.setDropDownViewResource(R.layout.sherlock_spinner_dropdown_item);
		reportTypeSpinner.setAdapter(reportTypeAdapter);

	

		int spinnerPosition1 = reportTypeAdapter.getPosition(reportTypeAdapter
				.getItem(0));
		reportTypeSpinner.setSelection(spinnerPosition1);
		reportTypeSpinner.setSelected(true);
		initMap();

	}

	private void initMap() {
		mMapController = mMapView.getController();
		mMapController.enableClick(true);
		mMapController.setZoom(zoomLevel);
		mMapView.setDoubleClickZooming(true);
		mMapView.setOnTouchListener(mapTouchListener);
		mSearch = new MKSearch();
		initMKSearch();
		graphicsOverlay = new GraphicsOverlay(mMapView);
		mMapView.getOverlays().add(graphicsOverlay);
		iv_address.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				mSearch.geocode(ed_address.getText().toString(), "");
			}
		});
	}

	private OnTouchListener mapTouchListener = new OnTouchListener() {
		@Override
		public boolean onTouch(View v, MotionEvent event) {
			int x = (int) event.getX();
			int y = (int) event.getY();
			switch (event.getAction()) {
			case MotionEvent.ACTION_DOWN:
				isMoved = false;
				mLastMotionX = x;
				mLastMotionY = y;
				mMapView.postDelayed(mLongPressRunnable, 1000);
				break;
			case MotionEvent.ACTION_MOVE:
				if (isMoved)
					break;

				if (Math.abs(mLastMotionX - x) > TOUCH_SLOP
						|| Math.abs(mLastMotionY - y) > TOUCH_SLOP) {
					isMoved = true;
					mMapView.removeCallbacks(mLongPressRunnable);
				}
				break;
			case MotionEvent.ACTION_UP:
				mMapView.removeCallbacks(mLongPressRunnable);
				break;
			default:
				break;
			}
			return false;
		}
	};
	/** 长按 */
	private Runnable mLongPressRunnable = new Runnable() {
		@Override
		public void run() {
			final GeoPoint pt = mMapView.getProjection().fromPixels(
					(int) mLastMotionX, (int) mLastMotionY);
			mSearch.reverseGeocode(pt);
		}
	};

	@Override
	public boolean handleMessage(Message msg) {
		try {
			switch (msg.what) {
			case AppContext.LOCATE:
				latitude = (int) (app.latitude * 1E6);
				longitude = (int) (app.longitude * 1E6);
				if (latitude != 0 && longitude != 0) {
					GeoPoint pt = new GeoPoint(latitude, longitude);
					currentPoint = pt;
					mSearch.reverseGeocode(pt);
					mMapController.animateTo(pt);
					OverlayItem item = new OverlayItem(pt, null, null);
					ItemizedOverlay<OverlayItem> overlay = new ItemizedOverlay<OverlayItem>(myLocation, mMapView);
					overlay.removeAll();
					overlay.addItem(item);
					mMapView.getOverlays().clear();
					mMapView.getOverlays().add(overlay);
					mMapView.refresh();
					mSearch.reverseGeocode(pt);
				}
				break;
			default:
				break;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	private void initMKSearch() {
		mSearch.init(app.mBMapManager, new MKSearchListener() {

			@Override
			public void onGetWalkingRouteResult(MKWalkingRouteResult res,
					int error) {
			}

			@Override
			public void onGetTransitRouteResult(MKTransitRouteResult res,
					int error) {
			}

			@Override
			public void onGetSuggestionResult(MKSuggestionResult res, int error) {
			}

			@Override
			public void onGetPoiResult(MKPoiResult res, int type, int error) {

			}

			@Override
			public void onGetPoiDetailSearchResult(int res, int error) {
			}

			@Override
			public void onGetDrivingRouteResult(MKDrivingRouteResult res,
					int error) {
			}

			@Override
			public void onGetBusDetailResult(MKBusLineResult res, int error) {
			}

			@Override
			public void onGetAddrResult(MKAddrInfo res, int error) {
				try {

					if (error != 0) {
						if (error == 100) {
							Toast.makeText(mainActivity,
									"解析失败,请正确输入地址：如XXX市XXX", Toast.LENGTH_LONG)
									.show();
							return;
						}
						return;
					}
					if (res.geoPt != null) {
						// TODO 还无保存
						latitude = res.geoPt.getLatitudeE6();
						longitude = res.geoPt.getLongitudeE6();
						currentPoint = res.geoPt;
						place = res.strAddr;
						OverlayItem item = new OverlayItem(res.geoPt, null,
								null);
						ItemizedOverlay<OverlayItem> overlay = new ItemizedOverlay<OverlayItem>(
								myLocation, mMapView);
						overlay.removeAll();
						overlay.addItem(item);
						mMapView.getOverlays().clear();
						mMapView.getOverlays().add(overlay);
						mMapView.refresh();
						testCircleClick(currentPoint, raidus);
						mMapController.setCenter(currentPoint);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}

		});
	}

	@Override
	public void onPause() {
		mMapView.onPause();
		super.onPause();
	}

	@Override
	public void onResume() {
		mMapView.onResume();
		super.onResume();
	}

	// @see
	// http://snipperize.todayclose.com/snippet/php/SQL-Query-to-Find-All-Retailers-Within-a-Given-Radius-of-a-Latitude-and-Longitude--65095/
	// The circumference of the earth is 24,901 miles.
	// 24,901/360 = 69.17 miles / degree
	/**
	 * @param raidus
	 *            单位米 return minLat,minLng,maxLat,maxLng
	 */
	// public static double[] getAround(double lat,double lon,int raidus){
	//
	// Double latitude = lat;
	// Double longitude = lon;
	//
	// Double degree = (24901*1609)/360.0;
	// double raidusMile = raidus;
	//
	// Double dpmLat = 1/degree;
	// Double radiusLat = dpmLat*raidusMile;
	// Double minLat = latitude - radiusLat;
	// Double maxLat = latitude + radiusLat;
	//
	// Double mpdLng = degree*Math.cos(latitude * (PI/180));
	// Double dpmLng = 1 / mpdLng;
	// Double radiusLng = dpmLng*raidusMile;
	// Double minLng = longitude - radiusLng;
	// Double maxLng = longitude + radiusLng;
	// //System.out.println("["+minLat+","+minLng+","+maxLat+","+maxLng+"]");
	// return new double[]{minLat,minLng,maxLat,maxLng};
	// }
	/**
	 * 画圆
	 * 
	 * @param pt1
	 * @param raidus
	 */
	public void testCircleClick(GeoPoint pt1, double raidus) {

		graphicsOverlay.removeAll();
		// 构建点并显示
		Geometry circleGeometry = new Geometry();

		circleGeometry.setCircle(pt1, (int) raidus);

		Symbol circleSymbol = new Symbol();
		Symbol.Color circleColor = circleSymbol.new Color();
		circleColor.red = 0;
		circleColor.green = 255;
		circleColor.blue = 0;
		circleColor.alpha = 126;
		circleSymbol.setSurface(circleColor, 1, 3);

		Graphic circleGraphic = new Graphic(circleGeometry, circleSymbol);
		graphicsOverlay.setData(circleGraphic);
		mMapView.getOverlays().add(graphicsOverlay);
		mMapView.refresh();
	}

	@Override
	public void execute(int mes, Object obj) {
		String response;
		HashMap<String, String> map;
		switch (mes) {
		case menu_confirm:
			String range = raidusString[rangeSpinner.getSelectedItemPosition()];
			map = new HashMap<String, String>();
			map.put("auth_token", AppContext.getInstance().getAuthToken());
			map.put("place", place);
			map.put("longitude", String.valueOf(longitude / 1E6));
			map.put("latitude", String.valueOf(latitude / 1E6));
			map.put("radius", range);
			map.put("type_id", String.valueOf(reportTypeSpinner.getSelectedItemPosition()));
			map.put("from", "android_app");
			response = HttpUtils.doPost(mainActivity,UrlConfig.cautions, map);
			Log.d("debug", "response---==>" + response);
			break;

		default:
			break;
		}
	}

	public void setAlarmMap(){
		UICore.eventTask(this, mainActivity, menu_confirm, null,true);
	}
	

}
